<template>
  <div class="groove-monitoring-page">
    <div class="breadcrumb">
      <Breadcrumb :data="breadcrumbData"></Breadcrumb>
    </div>
    <main>
      <div class="search-content">
        <div class="serach-item">
          <el-input
            v-model="searchAddress"
            placeholder="请输入地址"
            @keydown.native.enter="handleSearch">
          </el-input>
          <el-button type="primary" @click="handleSearch">
            <i class="el-icon-search"></i>
          </el-button>
        </div>
        <div class="search-select">
          <el-select
            v-show="monitor"
            class="monitor"
            placeholder="请选择监测点"
            v-model="deviceId">
            <el-option
              v-for="item in monitorList"
              :value="item.id"
              :label="item.name"
              :key="item.id">
              {{ item.name }}
            </el-option>
          </el-select>
          <el-select
            class="condition"
            placeholder="请选择分区"
            v-model="areaId">
            <el-option
              v-for="item in currentAreaList"
              :value="item.id"
              :label="item.areaName"
              :key="item.id"
              :title="item.areaName"
            >
            </el-option>
          </el-select>
          <el-date-picker
            class="condition"
            v-show="hasClock"
            v-model="clockTime"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
          <el-switch
            class="condition"
            v-model="lineFlag"
            active-text="管道">
          </el-switch>
          <el-switch
            class="condition"
            v-model="carFlag"
            active-text="车辆">
          </el-switch>
          <el-switch
            class="condition"
            v-model="monitor"
            active-text="监控">
          </el-switch>
          <el-switch
            class="condition"
            v-model="hasClock"
            active-text="打卡">
          </el-switch>
          <el-switch
            class="condition"
            v-model="constructionFlag"
            active-text="施工点">
          </el-switch>
          <el-switch
            class="condition"
            v-model="perimeter"
            active-text="周界">
          </el-switch>
        </div>
      </div>
      <div class="map-container">
        <div v-if="monitorList.length" :class="['echarts-content', monitor ? 'show' : 'hide']">
          <div class="echarts-item">
            <broken-line :options="setOptions()"></broken-line>
          </div>
          <div class="echarts-item"></div>
        </div>
        <div id="security-management-map"></div>
      </div>
      <el-dialog :visible.sync="imgVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
      <live-dialog
        :visible="liveVisible"
        :liveOptions="liveOptions"
        :videoConfig="videoConfig"
        @cancel="liveVisible = false">
      </live-dialog>
    </main>
  </div>
</template>

<script>
import Breadcrumb from '@/components/public/Breadcrumb';
import liveDialog from '@/components/project/security/liveDialog';
import brokenLine from '@/components/echarts/brokenLine';
import excavatingMachinery from '@/assets/images/car/excavating_machinery.png';
import pilingMachine from '@/assets/images/car/piling_machine.png';
import truckMountedCrane from '@/assets/images/car/truck_mounted_crane.png';
import longExcavatingMachinery from '@/assets/images/car/long_excavating_machinery.png';
import car from '@/assets/images/car/car.png';
import forklift from '@/assets/images/car/forklift.png';
import crane from '@/assets/images/car/crane.png';
import liveIcon from '@/assets/images/car/live-icon.png';
import historyImage from '@/assets/images/history.png';

export default {
  components: {
    brokenLine,
    Breadcrumb,
    liveDialog
  },
  data() {
    return {
      // 面包屑数据
      breadcrumbData: [
        { name: '安全管理' },
        { name: '沟槽监测' }
      ],
      searchAddress: '',
      areaId: '',
      carFlag: false, // 车辆
      lineFlag: false, // 管道
      monitor: false, // 监控
      constructionFlag: false, // 施工点
      // 打卡设置
      hasClock: false,
      // 周界
      perimeter: true,
      clockTime: '',
      // 打卡信息
      clockList: [],
      //
      currentPolyline: null,
      // 地图实例
      mapApp: null,
      // 地址解析器的实例
      geocoder: null,
      // 地图标注对象
      marker: null,
      // 创建的面对象
      polygon: null,
      // 当前标签对象
      labelApp: null,
      handler: null,
      // 回填坐标信息
      points: null,
      visible: false,
      // 分区列表
      areaList: [],
      // 缓存当前地图上已经显示的面信息
      areaCacheList: [],
      // 可绑定人员
      bindList: [],
      // 弹框操作状态
      type: 'add',
      // 绑定人员id集合
      bindIds: [],
      // 区域名称
      areaName: '',
      // 是否需要打卡 0：不需要；1：需要
      clockFlag: '0',
      // 区域类型
      areaType: '2',
      // 周界（工区）、机械（车辆等）、监控、管道、人员、施工点（排口、调蓄池）
      areaTypeList: [
        { name: '周界（工区）', id: '2' },
        { name: '施工点（排口、调蓄池）', id: '6' }
      ],
      // 当前所选区域的信息
      currentArea: null,
      // 区域坐标数据
      areaData: null,
      // 圆形半径设置
      currentRadius: null,
      lineDialogType: '',
      // 管道数据
      lineList: [],
      lineListCache: [],
      // 当前线段经纬度
      lineOptions: [],
      // 定位器id
      locatorId: '',
      // 车俩定位信息
      locationList: [],
      // 轨迹实例
      polyline: null,
      carTrackList: [],
      colorId: 'red',
      widthNum: 10,
      // 地图信息弹框图片显示
      imgVisible: false,
      dialogImageUrl: '',
      perimeterViews: [],
      lineViews: [],
      constructionViews: [],
      carViews: [],
      personnelViews: [],
      // 摄像头列表
      liveList: [],
      liveViews: [],
      liveLabels: [],
      videoConfig: {},
      liveVisible: false,
      liveOptions: {},
      // 沟槽
      monitorList: [],
      monitorHistoryObj: {
        arr_x: [],
        arr_y: []
      },
      monitornews: {},
      deviceId: ''
    };
  },
  computed: {
    projectId() {
      return this.$store.state.currentProjectId;
    },
    projectName() {
      return this.$store.state.currentProjectInfo.projectName;
    },
    // 打卡标注信息
    clockMarkerList() {
      /* eslint-disable */
        const result = [];
        this.clockList.forEach(item => {
          const { lat, lng } = item;
          if (!lat || !lng) return;
          const point = new T.LngLat(lng, lat);
          const marker = new T.Marker(point, {
            itemData: item
          });
          result.push(marker);  // 创建标注
          marker.addEventListener('click', this.handleMarkerClick)
        });
        return result;
      },
      // 矩形设置文件信息
      fileNames() {
        const { fileUrl } = this.areaData || {};
        const fileNames = fileUrl ? fileUrl.match(/([^\/])+\.\w+$/) : '';
        const fileName = Array.isArray(fileNames) ? fileNames[0] : '';
        const fileLink = fileUrl ? this.$checkUrl(fileUrl) : '';
        return {
          fileUrl,
          fileLink,
          fileName
        }
      },
      // 分区下拉列表数据
      currentAreaList() {
        let result = [];
        result = this.lineFlag ? [...this.lineAreaList] : [];
        result = this.carFlag
          ? [...result, ...this.carAreaList]
          : [...result];
        result = this.constructionFlag
          ? [...result, ...this.constructionList]
          : [...result];
        result = this.perimeter
          ? [...result, ...this.perimeterList]
          : [...result];
        return result;
      },
      // 周界类型数据
      perimeterList() {
        return this.areaList.filter(v => v.areaType === '2');
      },
      // 车辆类型数据
      carAreaList() {
        return this.areaList.filter(v => v.areaType === '3');
      },
      // 管道类型数据
      lineAreaList() {
        return this.areaList.filter(v => v.areaType === '1');
      },
      // 人员类型数据
      personnelAreaList() {
        return this.areaList.filter(v => v.areaType === '5');
      },
      // 施工点类型数据
      constructionList() {
        return this.areaList.filter(v => v.areaType === '6');
      },
      // 打卡标注信息
      carMarkerList() {
        /* eslint-disable */
        const result = [];
        this.locationList.forEach(item => {
          const { jing_du, wei_du, name } = item;
          if (!jing_du || !wei_du) return;
          const point = new T.LngLat(Number(jing_du), Number(wei_du));
          let iconUrl = '';
          if (/挖机/g.test(name)) iconUrl = excavatingMachinery;
          else if (/打桩/g.test(name)) iconUrl = pilingMachine;
          else if (/铲车/g.test(name)) iconUrl = forklift;
          else if (/长臂挖机/g.test(name)) iconUrl = longExcavatingMachinery;
          else if (/随车吊/g.test(name)) iconUrl = truckMountedCrane;
          else if (/起重机/g.test(name)) iconUrl = crane;
          else iconUrl = car;
          const icon = new T.Icon({
            iconUrl,
            iconSize: new T.Point(40, 40),
            // iconAnchor: new T.Point(10, 25)
          });
          const marker = new T.Marker(point, {
            icon,
            title: name,
            itemData: item
          });
          result.push({
            point,
            marker
          });  // 创建标注
          marker.addEventListener('click', this.handleCarMarkerClick)
        });
        return result;
      },
    },
  watch: {
    // 监听分区
    areaId(id) {
      if (id) {
        const currentItem = this.areaList.find(item => {
          return item.id === id;
        });
        if (!currentItem) return;
        this.pantoArea(currentItem);
      }
    },
    // 监听打卡开关
    hasClock(val) {
      if (!val) {
        this.setMarker(false);
        this.clockTime = '';
        return;
      }
      this.clockTime = this.$moment().format('YYYY-MM-DD');
    },
    monitor(val) {
      if (val) {
        this.liveViews = [];
        this.liveLabels = [];
        this.liveList.forEach((item, index) => {
          const result = this.setLiveMarker(item, index === 0);
          if (result) {
            const { marker, label } = result;
            marker && this.liveViews.push(marker);
            label && this.liveLabels.push(label);
          }
        });
        return;
      }
      this.clearLiveMarker();
    },
    // 监听周界开关 开启状态设置所有分区
    perimeter(val) {
      if (val) {
        this.perimeterViews = [];
        this.perimeterList.forEach((item, index) => {
          const view = this.setArea(item, index === 0);
          view && this.perimeterViews.push(view);
        });
        // this.currentArea = null;
        return;
      }
      this.clearArea(this.perimeterViews);
    },
    // 监听管道开关 开启状态设置所有分区
    lineFlag(val) {
      if (val) {
        this.lineViews = [];
        this.lineAreaList.forEach((item, index) => {
          const view = this.setArea(item, index === 0);
          view && this.lineViews.push(view);
        });
        // this.currentArea = null;
        return;
      }
      this.clearArea(this.lineViews, 'line');
    },
    // 监听施工点开关 开启状态设置所有分区
    constructionFlag(val) {
      this.clearArea(this.constructionViews);
      if (val) {
        this.constructionList.forEach((item, index) => {
          const view = this.setArea(item, index === 0);
          view && this.constructionViews.push(view);
        });
      }
    },
    // 监听车辆开关
    carFlag(val) {
      this.setCarMarker(val);
    },
    // 监听打卡时间
    clockTime(val) {
      if (val && this.hasClock) {
        this.setMarker(false);
        this.getStaffClockByDate();
      }
    },
    // 监听面对象
    polygon(val, oldVal) {
      if (val !== oldVal && oldVal) {
        oldVal.setColor('#FF1F28');
        oldVal.setFillColor('#0000FF');
      }
    },
    // 当前显示的区域
    currentAreaList(list, oldList) {
      const currentLen = list && list.length;
      const preLen = oldList ? oldList.length : 0;
      if (currentLen && currentLen !== preLen) {
        this.areaId = '';
        this.areaData = null;
        this.currentArea = null;
        this.mapApp.closeInfoWindow();
      }
    },
    deviceId(val) {
      if (val) {
        this.getTrenchDeviceListByDay();
        this.getTrenchHistoryList();
        this.getTrenchNewInfo();
      }
    }
  },
  mounted() {
    this.initMap();
    this.getTrenchDeviceList();
    this.getLiveToken();
    this.getBindStaffList();
    this.getSecurityAreaList(true);
    this.getVehicleLocatorList();
    window.mapImgClick = this.mapImgClick;
  },
  methods: {
    // 地图初始化
    initMap() {
      /* eslint-disable */
      const zoom = 14;
      const mapOptions = {
        datasourcesControl: true
      };
      this.mapApp = new T.Map('security-management-map', mapOptions);
      this.mapApp.centerAndZoom(new T.LngLat(116.40969, 39.89945), zoom);
      this.geocoder = new T.Geocoder();
      this.ctrl = new T.Control.MapType();
      this.mapApp.addControl(this.ctrl);
    },
    // 获取沟槽设备列表
    async getTrenchDeviceList() {
      const { success, data: {
        data
      }} = await this.$Model.getTrenchDeviceList({
        projectId: this.projectId
      });
      if (success && Array.isArray(data)) {
        this.monitorList = data;
        if (!this.deviceId) {
          this.deviceId = data[0] ? data[0].id : '';
        }
      }
    },
    // 获取沟槽设备的历史记录
    async getTrenchHistoryList() {
      const { success, data: {
        data
      }} = await this.$Model.getTrenchHistoryList({
        day: this.$moment().format('YYYY-MM-DD'),
        idDevice: this.deviceId,
        projectId: this.projectId
      });
      if (success && data) {
        this.monitorHistoryObj = data;
      }
    },
    // 获取沟槽设备一天的数据
    async getTrenchDeviceListByDay() {
      const { success, data: {
        data
      }} = await this.$Model.getTrenchDeviceListByDay({
        day: this.$moment().format('YYYY-MM-DD'),
        idDevice: this.deviceId,
        oriPage: 1,
        projectId: this.projectId
      });
      if (success && data) {
        this.monitornews = data;
      }
    },
    // 设备id获取沟槽设备最新的数据
    async getTrenchNewInfo() {
      const { success, data: {
        data
      }} = await this.$Model.getTrenchNewInfo({
        idDevice: this.deviceId,
        projectId: this.projectId
      });
      if (success && data) {}
    },
    /**
     * 获取所有摄像机的信息
     */
    async getLiveToken() {
      const { success, data } = await this.$Model.getameraList({
        project_name: this.projectName
      });
      if (success && data.data) {
        const result = data.data.data;
        this.liveList = Array.isArray(result) ? result : [];
      }
    },
    /**
     * 获取车辆定位数据
     * @param {?Boolean} hasPanto
     */
    async getVehicleLocatorList(hasPanto = false) {
      const { success, data: { data }} = await this.$Model.getVehicleLocatorList({
        projectId: this.projectId
      });
      if (success && Array.isArray(data)) {
        this.locationList = data;
        this.setCarMarker(false);
      }
    },
    /**
     * 根据定位器id获取当前定位器的历史轨迹
     * @param {?String} id 定位器id
     */
    async getHisLocatorById(id) {
      const { success, data: { data }} = await this.$Model.getHisLocatorById({
        locatorId: id || this.locatorId
      });
      if (success && Array.isArray(data)) {
        this.setCatTrack(data);
      }
    },
    /**
     * 查看历史记录
     * @param type {String} 配置类型
     */
    getHistory(type) {
      console.log('type', type);
    },
    /**
     * 设置当前定位点车辆的历史轨迹
     * @param {Array} list 轨迹坐标
     */
    setCatTrack(list) {
      this.polyline && this.mapApp.removeOverLay(this.polyline);
      this.carTrackList = list
        .filter((item) => item.jing_du && item.wei_du)
        .map(item => {
          const { jing_du, wei_du } = item;
          return new T.LngLat(Number(jing_du), Number(wei_du));
        });
      this.polyline = new T.Polyline(this.carTrackList);
      this.mapApp.addOverLay(this.polyline);
    },
    /**
     * 设置车辆标记点
     * @param {?Boolean} hasShow true: 展示
     * @param {?Boolean} hasPanto 是否到视图中心
     */
    setCarMarker(hasShow = false, hasPanto) {
      this.carMarkerList.forEach(({ marker, point }, index) => {
        if (hasShow) {
          this.mapApp.addOverLay(marker);
          hasPanto && index === 0 && this.mapApp.panTo(point, 8);
          return;
        }
        this.mapApp.removeOverLay(marker);
      });
    },
    /**
     * 标注的点击事件
     */
    handleCarMarkerClick(e) {
      const { lnglat, target: { options: { itemData }}} = e;
      const contentStr = `<div style="background: #232350; color: #bac4ff;">
                        <p style="text-align: center;">详细信息</p>
                        <div style="line-height: 25px;">定位器名称：${itemData.name || ''}</div>
                        <div style="line-height: 25px;">定位器类型：${itemData.type || ''}</div>
                        <div style="line-height: 25px;">电量：${itemData.electricity || ''}</div>
                        <div style="line-height: 25px;">绑定车辆名称 ：${itemData.name_bind || ''}</div>
                      </div>`;
      const infoWin = new T.InfoWindow();
      infoWin.setContent(contentStr);
      this.mapApp.openInfoWindow(infoWin, lnglat);
      this.locatorId = itemData.id;
      this.getHisLocatorById(itemData.id)
    },
    // 开关清除对应地图覆盖物
    clearArea(list) {
      if (!list) return;
      list.forEach(item => {
        const { view, labelApp, data: { areaType } } = item;
        labelApp && this.mapApp.removeOverLay(labelApp);
        if (areaType === '1') {
          view && view.forEach(({ line }) => {
            line && this.mapApp.removeOverLay(line);
          });
          return;
        }
        view && this.mapApp.removeOverLay(view);
      });
      list = [];
    },
    // 查看附件地图
    mapImgClick(fileLink) {
      this.dialogImageUrl = fileLink;
      this.imgVisible = true;
    },
    /**
     * 切换视图中心
     * @param {Object} data
     */
    pantoArea(data = {}) {
      const { areaData } = data;
      if (this.$checkType(areaData) !== 'object' || !this.mapApp) return;
      const { points, type } = areaData;
      this.areaData = areaData;
      // 转换之后的数据
      this.currentArea = { ...data, areaData };
      if (type === 'line' && points && points[0]) {
        const linePoints = points[0].points && points[0].points[0];
        linePoints && this.mapApp.panTo(linePoints, 14);
        return;
      }
      const newPoints = this.setPoints(points);
      // 设置地图位置中心
      newPoints[0] && this.mapApp.panTo(newPoints[0], 14);
    },
    /**
     * 设置摄像头位置
     * @param {Object} item: 摄像头信息
     * @param {Boolean} hasPanto
     * @returns {Object | Boolean}
     */
    setLiveMarker(item, hasPanto = false) {
      if (!item) return;
      const { jing_du, wei_du } = item;
      if (!jing_du || !wei_du) return;
      const point = new T.LngLat(Number(jing_du), Number(wei_du));
      const icon = new T.Icon({
        iconUrl: liveIcon,
        iconSize: new T.Point(35, 40),
      });
      const marker = new T.Marker(point, {
        icon,
        // title: item.name_device || '',
        itemData: item,
        point
      });
      const label = new T.Label({
        text: `<b style="color: #0000FF;">${item.name_device}<b>`,
        itemData: { ...item },
        position: point,
        offset: new T.Point(-50, -35)
      });
      this.mapApp.addOverLay(marker);
      this.mapApp.addOverLay(label);
      hasPanto && this.mapApp.panTo(point);
      marker.addEventListener('click', this.handleLiveMarkerClick);
      label.addEventListener('click', this.handleLiveMarkerClick);
      return {
        marker,
        label
      };
    },
    // 清除摄像头标记
    clearLiveMarker() {
      this.liveViews.forEach(marker => {
        marker.removeEventListener('click', this.handleLiveMarkerClick);
        this.mapApp.removeOverLay(marker);
      });
      this.liveLabels.forEach(label => {
        label.removeEventListener('click', this.handleLiveMarkerClick);
        this.mapApp.removeOverLay(label);
      });
      this.liveLabels = [];
      this.liveViews = [];
    },
    /**
     * 摄像头位置点击
     */
    handleLiveMarkerClick(e) {
      const { lnglat, target: { options: { itemData }}} = e;
      this.setVideoConfig(itemData);
    },
    /**
     * 设置直播配置
     * @param options {Object}
     */
    setVideoConfig(options) {
      const { access_token, nums_device, passageway } = options;
      this.videoConfig = {
        accessToken: access_token,
        url: `ezopen://open.ys7.com/${nums_device}/${passageway}.hd.live`
      };
      this.liveOptions = options;
      this.liveVisible = true;
    },
    /**
     * 设置当前的视图数据
     */
    setView(view, areaType) {
      if (!view) return;
      const checkFn = (data, list) => {
        const { data: { id } = {} } = data;
        return list.some(item => item.id === id);
      };
      switch (areaType) {
        case '1':
          !checkFn(view, this.lineViews) && this.lineViews.push(view);
          break;
        case '2':
          !checkFn(view, this.perimeterViews) && this.perimeterViews.push(view);
          break;
        case '3':
          !checkFn(view, this.carViews) && this.carViews.push(view);
          break;
        case '5':
          !checkFn(view, this.personnelViews) && this.personnelViews.push(view);
          break;
        case '6':
          !checkFn(view, this.constructionViews) && this.constructionViews.push(view);
          break;
      }
    },
    /**
     * 设置地图分区
     * @param {Object} data 单个分区数据
     * @param {?Boolean} hasPanto 是否设置中心
     * @param {?Boolean} hasInit 是否全量设置
     */
    setArea(data = {}, hasPanto = true, hasInit = false) {
      if (!data
        || this.$checkType(data.areaData) !== 'object'
        || !this.mapApp) return;
      const areaData = data.areaData;
      const { points, type } = areaData;
      if (!Array.isArray(points)) return;
      const currentAreaData = { ...data, areaData };
      if (!hasInit) {
        this.areaData = areaData;
        // 转换之后的数据
        this.currentArea = currentAreaData;
      }
      // 新增类型 line: 管道，polygon：多边形，circular：圆
      if (type === 'line') {
        return this.setLine(currentAreaData, hasPanto, hasInit);
      } else if (type === 'circular') {
        return this.setCircle(currentAreaData, hasPanto, hasInit);
      } else if (type === 'polygon') {
        return this.setPolygon(currentAreaData, hasPanto, hasInit);
      }
    },
    // 设置坐标
    setPoints(points) {
      if (!(Array.isArray(points) && points.length)) return;
      return points
        .filter(item => {
          const clng = String(item.lng);
          const clat = String(item.lat);
          return !isNaN(clng) && !isNaN(clat);
        }).map(item => {
          return new T.LngLat(Number(item.lng), Number(item.lat));
        });
    },
    /**
     * 设置圆形区域
     * @param {Object} data: 当前设置区域的数据
     * @param {?Boolean} hasPanto 是否设置中心
     * @param {?Boolean} hasInit 是否全量设置
     */
    setCircle(data, hasPanto, hasInit = false) {
      const { areaData, areaType } = data;
      const { points, currentRadius, type } = areaData;
      const newPoints = this.setPoints(points);
      if (!newPoints) return;
      // 设置圆形显示区域
      const LngLat = newPoints[0];
      // 设置分区名称标注
      let color = 'green';
      if (areaType === '6') color = '#04FF00';
      const labelApp = new T.Label({
        text: `<b style="color: ${color};">${data.areaName}<b>`,
        itemData: {
          ...data
        },
        position: LngLat,
        offset: new T.Point(-35, 0)
      });
      const circle = new T.Circle(LngLat, Number(currentRadius), {
        color: '#FF1F28',
        fillColor: '#0000FF',
        itemData: {
          ...data
        },
        LngLat,
        labelApp
      });
      labelApp.addEventListener('click', (e) => this.polygonClick(e, circle, labelApp));
      if (!hasInit) {
        this.polygon = circle;
        this.labelApp = labelApp;
      }
      // 向地图上添加圆
      this.mapApp.addOverLay(circle);
      // 向地图上添加分区标注
      this.mapApp.addOverLay(labelApp);
      // 设置地图位置中心
      hasPanto && this.mapApp.panTo(LngLat, 14);
      return {
        labelApp,
        view: circle,
        data
      };
    },
    /**
     * 设置多边形区域
     * @param {Object} data: 当前设置区域的数据
     * @param {?Boolean} hasPanto 是否设置中心
     * @param {?Boolean} hasInit 是否全量设置
     */
    setPolygon(data, hasPanto, hasInit = false) {
      const { areaData, areaType } = data;
      const { points, type } = areaData;
      const newPoints = this.setPoints(points);
      if (!newPoints) return;
      // 获取区域中心
      const centers = this.mapApp.getViewport(newPoints);
      // 设置分区名称标注
      let color = 'green';
      if (areaType === '6') color = '#04FF00';
      const labelApp = new T.Label({
        text: `<b style="color: ${color};">${data.areaName}<b>`,
        position: centers ? centers.center : newPoints[0],
        offset: new T.Point(-40, 0),
        itemData: {
          ...data
        }
      });
      // 创建面对象
      const polygon = new T.Polygon(newPoints, {
        color: '#FF1F28',
        fillColor: '#0000FF',
        itemData: {
          ...data
        },
        newPoints,
        labelApp
      });
      labelApp.addEventListener('click', (e) => this.polygonClick(e, polygon, labelApp));
      if (!hasInit) {
        this.polygon = polygon;
        this.labelApp = labelApp;
      }
      // 向地图上添加面
      this.mapApp.addOverLay(polygon);
      // 向地图上添加分区标注
      this.mapApp.addOverLay(labelApp);
      // 设置地图位置中心
      hasPanto && this.mapApp.panTo(newPoints[0], 14);
      return {
        labelApp,
        view: polygon,
        data
      };
    },
    /**
     * 设置管道
     * @param {Object} data 当前管道数据
     * @param {Boolean} hasPanto 是否设置中心
     * @param {Boolean} hasInit 是否显示区域
     */
    setLine(data, hasPanto, hasInit = false) {
      const { areaData: { points: lines }} = data;
      if (!Array.isArray(lines) || !lines.length) return;
      let labelApp = null;
      const currentLineList = [];
      lines.forEach((item, index) => {
        const { points, options } = item;
        // 创建线段对象
        const line = item.line
          ? item.line
          : new T.Polyline(points, {
            itemData: {
              ...data
            },
            ...options
          });
        if (index === 0) {
          // 设置管道名称标注
          const position = points[1] || points[0];
          labelApp = new T.Label({
            position,
            itemData: {
              ...data
            },
            text: `<b style="color: red;">${data.areaName}<b>`,
            // offset: new T.Point(20, 0)
          });
          // 向地图上添加分区标注
          this.mapApp.addOverLay(labelApp);
          // 设置地图位置中心
          hasPanto && this.mapApp.panTo(position, 14);
        }
        currentLineList.push({
          ...item,
          line
        });
        // 向地图上添加线段
        this.mapApp.addOverLay(line);
      });
      if (!hasInit) {
        this.lineListCache = [...this.lineList];
        this.labelApp = labelApp;
        this.lineList = [...currentLineList];
      }
      labelApp.addEventListener('click', (e) => this.lineClick(e, currentLineList, labelApp));
      return {
        labelApp,
        view: [...currentLineList],
        data
      };
    },
    /**
     * 面的点击事件
     */
    polygonClick(e, polygon, labelApp) {
      const { lnglat, target: { options: { itemData }}} = e;
      if (polygon) {
        polygon.setColor('#2eb76f');
        this.polygon = polygon;
      }
      const { areaName, id, userIds, areaData, areaType } = itemData || {};
      this.currentArea = itemData;
      this.areaData = { ...areaData };
      this.labelApp = labelApp;
      this.areaId = id;
      let userStr = '';
      if (userIds) {
        const userList = userIds.split(',');
        userList.length && userList.forEach((userId, i) => {
          const currentUser = this.bindList.find(val => {
            return val.userId === userId;
          });
          if (currentUser) {
            userStr += `${i === 0 ? '' : '、'}${currentUser.userName}`;
          }
        });
      }
      const { remark, fileUrl } = areaData;
      const fileNames = fileUrl ? fileUrl.match(/([^\/])+\.\w+$/) : '';
      const fileName = Array.isArray(fileNames) ? fileNames[0] : '';
      const fileLink = fileUrl ? this.$configs.upload + fileUrl : '';
      const hasImg = /(\.jpg|\.jpeg|\.png)$/.test(fileLink);
      const currentType = this.areaTypeList.find(v => v.id === areaType);
      const contentStr = `<div style="">
                        <p>详细信息</p>
                        <div style="line-height: 20px">区域名称：${areaName}</div>
                        <div style="line-height: 20px">绑定人员：${userStr || '暂无'}</div>
                        <div style="line-height: 20px">类型：${currentType ? currentType.name : '暂无'}</div>
                        <div style="line-height: 20px">附件：${fileLink ? `${hasImg
        ? `<img src="${fileLink}" onclick="mapImgClick('${fileLink}')" style="width: 200px; height: 100px"/>`
        : `<a href="${fileLink}" target="_blank">${fileName || '附件'}</a>`}` : ''}</div>
                        <div style="line-height: 20px">备注：${remark || '暂无'}</div>
                      </div>`;
      const infoWin = new T.InfoWindow();
      infoWin.setContent(contentStr);
      this.mapApp.openInfoWindow(infoWin, lnglat);
    },
    /**
     * 管道点击事件
     */
    lineClick(e, lineList, labelApp) {
      const { lnglat, target: { options: { itemData = {} }}} = e;
      const { areaData = {}, areaName, id } = itemData;
      const { lineDetails, points } = areaData;
      const {
        lineType = '',
        totalLen = '',
        completeLen = '',
        undoneLen = '',
        remark = '',
        pipeDiameter = '',
        sectionName = ''
      } = lineDetails || {};
      this.currentArea = itemData;
      this.lineList = [...lineList];
      this.lineListCache = [...lineList];
      this.areaId = id;
      this.labelApp = labelApp;
      const contentStr = `<div style="">
                        <p>详细信息</p>
                        <div style="line-height: 20px">管道名称：${areaName}</div>
                        <div style="line-height: 20px">路段名称：${sectionName}</div>
                        <div style="line-height: 20px">管道类型：${lineType}</div>
                        <div style="line-height: 20px">管径：${pipeDiameter}</div>
                        <div style="line-height: 20px">管道总长度：${totalLen}</div>
                        <div style="line-height: 20px">已完成长度：${completeLen}</div>
                        <div style="line-height: 20px">未完成长度：${undoneLen}</div>
                        <div style="line-height: 20px">备注：${remark}</div>
                      </div>`;
      const infoWin = new T.InfoWindow();
      infoWin.setContent(contentStr);
      this.mapApp.openInfoWindow(infoWin, lnglat);
    },
    /**
     * 标注的点击事件
     */
    handleMarkerClick(e) {
      const { lnglat, target: { options: { itemData }}} = e;
      const { areaName, userName, finishFlag, clockTime } = itemData;
      const contentStr = `<div style="background: #232350; color: #bac4ff;">
                        <p style="text-align: center;">详细信息</p>
                        <div style="line-height: 25px;">区域名称：${areaName}</div>
                        <div style="line-height: 25px;">姓名：${userName}</div>
                        <div style="line-height: 25px;">位置：打卡${finishFlag === '1' ? '成功' : '失败'}</div>
                        <div style="line-height: 25px;">打卡日期：${clockTime}</div>
                      </div>`;
      const infoWin = new T.InfoWindow();
      infoWin.setContent(contentStr);
      this.mapApp.openInfoWindow(infoWin, lnglat);
    },
    /**
     * 地址搜索
     */
    handleSearch() {
      /* eslint-disable */
      if (!this.geocoder) return;
      const hasAddress = /^(\s+)$/g.test(this.searchAddress);
      if (hasAddress) return;
      this.geocoder.getPoint(this.searchAddress, (res) => {
        if (res.getStatus() === 0) {
          const point = res.getLocationPoint();
          this.mapApp.panTo(point, 14);
          this.marker && this.mapApp.removeOverLay(this.marker);
          // 创建标注对象
          this.marker = new T.Marker(point);
          // 向地图上添加标注
          this.mapApp.addOverLay(this.marker);
          return;
        }
        this.$message.warning(res.getMsg() || '地址解析异常');
      });
    },
    /**
     * 设置标记点
     * @param {?Boolean} hasShow true: 展示
     */
    setMarker(hasShow = true) {
      this.clockMarkerList.forEach(marker => {
        if (hasShow) {
          this.mapApp.addOverLay(marker);
          return;
        }
        this.mapApp.removeOverLay(marker);
      });
    },
    /**
     * 删除管道线段
     * @param {?Object} data 当前删除的某条线段
     */
    removeLine(data) {
      if (data) {
        this.mapApp.removeOverLay(data);
        return;
      }
      this.lineList.forEach(item => {
        const { line } = item;
        line && this.mapApp.removeOverLay(line);
      });
    },
    /**
     * 获取打卡人员列表
     */
    async getStaffClockByDate() {
      const { success, data: { data }} = await this.$Model.getStaffClockByDate({
        type: '1',
        projectId: this.projectId,
        clockTime: this.hasClock ? this.clockTime : ''
      });
      if (success && Array.isArray(data)) {
        const list = data.filter(v => v.finishFlag === '1');
        this.clockList = list;
        this.setMarker();
        const item = list.find(val => val.lat && val.lng);
        if (item) {
          const { lat, lng } = item;
          if (!lat || !lng) return;
          const point = new T.LngLat(lng, lat);
          this.mapApp.panTo(point, 14);
        }
      }
    },
    /**
     * 获取区域列表数据
     * @param {Boolean} hasInit 是否显示区域
     */
    async getSecurityAreaList(hasInit = false) {
      const { success, data: { data }} = await this.$Model.getSecurityAreaList({
        pageFlag: false,
        projectId: this.projectId
      });
      if (success && data) {
        const list = data.list || [];
        this.areaList = list.map(item => {
          let areaData = {};
          try {
            areaData = typeof item.areaData === 'string'
              ? JSON.parse(item.areaData)
              : item.areaData;
          } catch (e) {}
          return {
            ...item,
            areaData
          };
        });
        if (this.perimeter && hasInit) {
          this.perimeterList.forEach((item, index) => {
            const view = this.setArea(item, index === 0);
            if (view) {
              this.perimeterViews.push(view);
            }
          });
        }
      }
    },
    // 获取可绑定的人员列表
    async getBindStaffList(options = {}) {
      const { success, data: { data }} = await this.$Model.getBindStaffList({
        projectId: this.projectId,
        ...options
      });
      if (success && Array.isArray(data)) {
        this.bindList = data;
      }
    },
    /**
     * 设置图表配置
     * @param title {Object} 设置标题信息
     * @param series {Object|Array} 设置数据
     * @param xAxis {Object|Array} 设置X轴
     * @param config {Object} 其它配置
     */
    setConfig({ title, series, xAxis, ...config }) {
      const defaultConfig = {
        title: {
          padding: [10, 0, 0, 10],
          textStyle: {
            color: '#fff',
            fontSize: this.$setRem(17, false)
          },
        },
        series: [
          {
            type: 'line',
            smooth: false,
            data: [],
            itemStyle: {
              normal: {
                color: 'rgba(42, 155, 248)', // 改变折线点的颜色
                lineStyle: {
                  color: 'red' // 改变折线颜色
                }
              }
            },
            markLine: {
              lineStyle: {
                color: 'red',
                type: 'solid'
              }
            }
          }
        ],
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.monitorHistoryObj.arr_x || [],
          axisLine: { // 轴线
            show: false,
            lineStyle: {
              color: 'rgb(42, 155, 248)'
            }
          },
          axisTick: { // 刻度
            show: true
          },
          axisLabel: {
            show: false,
            color: 'rgb(42, 155, 248)'
          }
        },
        toolbox: {
          itemSize: 20,
          iconStyle: {
            color: 'red'
          },
          emphasis: {
            iconStyle: {
              color: 'rgb(42, 155, 248)'
            }
          },
        },
        feature: {
          myTool1: {
            show: true,
            title: '查看历史记录',
            icon: `image://${historyImage}`,
            onclick: () => {
              this.getHistory();
            }
          }
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            // end: 50,
            // minValueSpan: 5,
            // maxValueSpan: 5,
            zoomLock: false
          }
        ]
      };
      if (this.$checkType(title) === 'object') {
        defaultConfig.title = {
          ...defaultConfig.title,
          ...title
        };
      }
      if (this.$checkType(xAxis) === 'object') {
        defaultConfig.xAxis = {
          ...defaultConfig.xAxis,
          ...xAxis
        };
      }
      if (Array.isArray(series)) {
        defaultConfig.series = series;
      } else if (this.$checkType(series) === 'object') {
        Object.keys(series).forEach(key => {
          defaultConfig.series[0][key] = series[key];
        });
      }
      if (this.$checkType(config) === 'object') {
        Object.assign(defaultConfig, config);
      }
      return defaultConfig;
    },
    setOptions() {
      const title = { text: '沟槽深度实时监测' };
      const series = {
        name: title.text,
        data: (this.monitorHistoryObj.arr_y || []).map(Number),
      };
      return this.setConfig({ title, series });
    }
  }
  };
</script>

<style scoped lang="scss">
  @import '../../../assets/styles/table';
  @import '../../../assets/styles/dialog';

  .groove-monitoring-page {
    width: 100%;
    height: 100%;
    background-color: $baseBg;
    color: #fff;
    main {
      width: 100%;
      height: calc(100% - 40px);
      padding: 20px;
      border-radius: 10px;
      .search-content {
        width: 100%;
        height: 80px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 20px;
        .serach-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          .el-input {
            width: 240px;
          }
          .el-button {
            margin-left: 20px;
          }
        }
        .condition {
          margin-left: 30px;
          /deep/ .el-switch__label {
            color: #fff;
          }
        }
        .monitor {
          width: 120px;
        }
      }
      .map-container {
        width: 100%;
        height: calc(100% - 80px);
        position: relative;
        overflow: hidden;
        #security-management-map {
          width: 100%;
          height: 100%;
        }
        .echarts-content {
          width: 500px;
          height: 100%;
          position: absolute;
          top: 0;
          left: 0;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          align-items: center;
          z-index: 1001;
          @include baseBgRgba();
          transition: all .3s;
          &.show {
            transform: translateX(0%);
          }
          &.hide {
            transform: translateX(-100%);
          }
          .echarts-item {
            width: 100%;
            height: 50%;
          }
        }
      }
    }
  }
</style>
